const model = require('../../public/model/env.js');
// const background = tt.getStorageSync('background');
const byteid = model.byteid();
const url = model.api_pro_url();
const key = model.key();
const appid = model.appid();
const userid = tt.getStorageSync('userid');
let eventSourceTask;


Page({
  data: {
    imId: byteid,
    className: 'containerdark',
    orderid: '',
    guixian: '',
    zhushu: '',
    zhanshi: '',
    responseData: '',
    showModal: true,
    sjvalue: '',
    nikename: '你好，道友',
    userid: '',
    showcontent: '1',
    buttonDisabled: false,
    code: 0,
    btn_area: '福生无量',

    over: null,
    mybaziresult: undefined,
  },
  requestbazi() {
    this.baziresult();
  },
  over() {
    this.setData({
      showModal: false
    });

  },
  imCallback(e) {
    console.log("跳转IM客服成功", e.detail);
  },
  onimError(e) {
    console.log("拉起IM客服失败", e.detail);
  },
  requestjieguo() {

    this.setData({
      buttonDisabled: true,
    });
    if (this.data.code == 400) {
      tt.showToast({ title: '不可重复解读', icon: 'loading', duration: 2000 });
      this.setData({
        buttonDisabled: false,
      });
    }



    if (this.data.code == 402) {
      tt.showToast({ title: '卦象正在请求中', icon: 'loading', duration: 2000 });
      const url = `https://dingvip.com/index.php?input=${this.data.sjvalue}`;
      // const url = "https://dingvip.com/index.php?input=你好";
      console.log('qin' + url);
      eventSourceTask = tt.createEventSource({ url });
      eventSourceTask.onMessage((res) => {
        console.log('eventSource res:', res.data); // 添加调试日志
        if (res.data === '[DONE]') {
          console.log('eventSource 完成');
          this.closeEventSource();
          return;
        }



        try {
          const jsondata = JSON.parse(res.data);
          if (jsondata && jsondata.choices && jsondata.choices[0] && jsondata.choices[0].delta && jsondata.choices[0].delta.content) {
            const content = jsondata.choices[0].delta.content;
            console.log('原始内容:', content); // 调试日志：输出原始内容
            const formattedContent = content
              .replace(/\n\n/g, '<br style="margin-top: 1rpx;">')
              .replace(/-/g, '&nbsp;&nbsp;')
              .replace(/####/g, '<hr>')
              .replace(/###/g, '<h3 class="fa fa-hand-o-right"></h3>')
              .replace(/\*\*/g, '')
              //  .replace(/>/g, '&gt;')
              .replace(/---/g, '');
            console.log('格式化后的内容:', formattedContent); // 调试日志：输出格式化后的内容
            this.setData({
              code: 400,
              showModal: true,
              responseData: this.data.responseData + formattedContent

                // .replace(/###([^#]+)###/g, '<div style="text-align: left;">$1</div>')
                .replace(/\*\*([^*]+)\*\*/g, '<text style="font-weight: bold">$1</text>'),
            });
          }
        } catch (e) {
          // console.error('JSON 解析错误:', e);
          console.log('res.data:', res.data); // 输出导致错误的原始数据
        }

      });
    }






  },
  closeModal() {
    if (this.data.btn_area == '返回个人中心') {
      this.setData({
        showModal: false,
        buttonDisabled: false,

      });

      tt.navigateTo({
        url: '../my/my'
      });
      return;
    }
    const requestUrl = `${url}/index.php/api/guaadd`;
    // console.log(key,appid,requestUrl);
    const options = {
      url: requestUrl,
      data: {
        appid: appid,
        key: key,
        userid: this.data.userid,
        pay_order_no: this.data.orderid,
        can: 1,
        zanbocontents: this.data.responseData,
        zhanbugua: this.data.guixian,
        zhanbubianyao: this.data.zhushu,
        zhanbuthing: this.data.zhanshi,
        buttonDisabled: false,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    console.log(options);
    tt.request({
      ...options,
      success: (res) => { // 使用箭头函数，无需定义that
        console.log("请求成功", res.data);
        tt.showToast({
          title: "解读数据已保存",
          icon: "success"
        });
      },
    });


    this.setData({
      showModal: false,
      buttonDisabled: false,
      // showcontent: '2'
    });

  },

  myCenter: function () {
    tt.navigateTo({
      url: '../my/my'
    });
  },
  input: function () {
    // 1111111111111111111111111111111111111111111111
    const requestUrl = `${url}/index.php/api/guaadd`;
    const options = {
      url: requestUrl,
      data: {
        // appid: appid,
        key: key,
        userid: this.data.userid,
        can: 3,
        pay_order_no: this.data.orderid,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    console.log(options);
    // 111111111111111111111111111111111111111111111111
    tt.request({
      ...options,
      success: (res) => { // 使用箭头函数，无需定义that
        console.log("请求成功", res.data);
        this.setData({ code: res.data.code, });
        if (res.data.code == 400) {
          tt.showToast({
            title: '查询成功',
            icon: "success"
          });
          this.setData({
            btn_area: '返回个人中心',
            showModal: true,
            responseData: res.data.data[0].zanbocontents,
            buttonDisabled: false,

          });
        } else {
          tt.showToast({
            title: '查询失败',
            icon: "none"
          });
        }
      },
    });
  },
  baziresult: function () {
    if (this.data.mybaziresult == undefined) {
      // console.log(this.data.sjvalue);
      const requestUrl = `${url}/index.php/api/bazi_list.php`;

      const options = {
        url: requestUrl,
        data: {
          user_id: userid,
          key: key,
        },
        method: 'GET',
        header: {
          'content-type': 'application/json'
        },
        dataType: 'json',
      };
      // console.log(options);
      tt.request({
        ...options,
        success: (res) => {
          const data = res.data;
          console.log(data.data.bazi);
          if (data.data.bazi !== '') {
            this.setData({
              mybaziresult: data.data.bazi,
              sjvalue: this.data.sjvalue + '我的生辰是（公历）' + data.data.bazi + '。',
            });
            // console.log(this.data.sjvalue);
            tt.showModal({

              title: '查询到',
              content: '查询到您的生辰八字：',
            });

          } else {
            tt.showModal({

              title: '未设置',
              content: '去个人中心设置生辰八字',

              showCancel: true,
              confirmText: '去设置',
              success: (res) => {
                if (res.confirm) {
                  tt.navigateTo({
                    url: '../my/my'
                  });
                }
              },
            });
          }
        },
        fail: (err) => {
        }
      });
    }else {
      tt.showToast({
        title: '已设置',
        icon: "none"
      });
      }
  },
  deepseek: function (deepseek_data) {
    const requestUrl = `${url}/index.php/api/dpsk.php`;
    const options = {
      url: requestUrl,
      data: {
        appid: appid,
        key: key,
        // user_id: userid,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(options);
    return new Promise((resolve, reject) => {
      tt.request({
        ...options,
        success: (res) => {
          const data = res.data;
          // console.log(data.data[0].jsontxt);
          if (data.code == 200) {
            deepseek_data = data.data[0].jsontxt;
            // console.log(deepseek_data); // 请求成功后打印 deepseek_data 的值
          }
          resolve(deepseek_data);
        },
        fail: (err) => {
          reject(err);
        }
      })
    })
  },
  //  结束
  onLoad: function (options) {
    const deepseek_data = undefined;
    this.deepseek(deepseek_data).then((modifiedE) => {

      // console.log("111111111111111999999999", modifiedE);
      this.setData({
        sjvalue: this.data.sjvalue + modifiedE,
      });
    });





    // console.log(options);

    let orderid = options.orderid;
    let zhanshi = options.order_thing;
    let guixian = options.order_gua;
    let zhushu = options.order_bianyao;
    let order_p = options.order_p;
    let userid = tt.getStorageSync('userid');
    const nickname = tt.getStorageSync('userInfo');
    // const deepseek_datas = deepseek_data;
    // console.log(nickname.nickName);
    this.setData({
      nikename: nickname.nickName,
      userid: userid,
      orderid: orderid,
      zhanshi: zhanshi,
      guixian: guixian,
      zhushu: zhushu,
      showModal: false,
      sjvalue: '卦象：' + guixian + '，变爻：' + zhushu + '，事情：' + zhanshi + ',请使用周易占卜解析，综合分析。',
    });
    console.log("123123123" + order_p);
    if (order_p == '202') {
      const requestUrl = `${url}/index.php/api/add_gua.php`;
      const sevgua = {
        url: requestUrl,
        data: {

          key: key,
          zhanbugua: this.data.guixian,
          zhanbubianyao: this.data.zhushu,
          zhanbuthing: this.data.zhanshi,
          userid: this.data.userid,
          pay_order_no: this.data.orderid,
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        dataType: 'json',
      };
      // console.log(sevgua);
      tt.request({
        ...sevgua,
        success: (res) => { // 使用箭头函数，无需定义that
          console.log("请求成功", res.data);
        }
      });
    }

    // 1111111111111111111111111111111111111111111111
    const requestUrl = `${url}/index.php/api/guaadd`;
    const options = {
      url: requestUrl,
      data: {
        // appid: appid,
        key: key,
        userid: this.data.userid,
        can: 3,
        pay_order_no: this.data.orderid,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      dataType: 'json',
    };
    // console.log(options);
    // 111111111111111111111111111111111111111111111111
    tt.request({
      ...options,
      success: (res) => { // 使用箭头函数，无需定义that
        console.log("请求成功", res.data);
        this.setData({ code: res.data.code, });
        if (res.data.code == 400) {
          tt.showToast({
            title: '查询成功',
            icon: "success"
          });
          this.setData({
            btn_area: '返回个人中心',
            showModal: true,
            responseData: res.data.data[0].zanbocontents,
            buttonDisabled: false,
            over: 'over',
          });
        }
      },
    });




  }
})